using System;
using System.Windows.Forms;
using DevExpress.XtraEditors.DXErrorProvider;

namespace Comteck.Winforms.Utils {
  /// <summary>
  /// 自定义验证规则
  /// </summary>
  public class DelegateValidationRule : ValidationRuleBase {
    private readonly Func<Control, object, ValidationResult> _validationFunc;

    /// <summary>
    /// ctor
    /// </summary>
    /// <param name="validationFunc"></param>
    public DelegateValidationRule(Func<Control, object, ValidationResult> validationFunc) {
      _validationFunc = validationFunc;
    }

    /// <summary>
    /// 拷贝
    /// </summary>
    /// <returns></returns>
    public override object Clone() {
      return this.MemberwiseClone();
    }

    /// <summary>
    /// 返回验证结果
    /// </summary>
    /// <param name="control"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public override bool Validate(Control control, object value) {
      ValidationResult result = _validationFunc(control, value);
      this.ErrorText = result.ErrorMessage;
      return result.IsValid;
    }
  }

  /// <summary>
  /// 验证结果类
  /// </summary>
  public class ValidationResult {
    /// <summary>
    /// 验证结果：true=成功，false=失败
    /// </summary>
    public bool IsValid { get; set; }
    /// <summary>
    /// 错误消息
    /// </summary>
    public string ErrorMessage { get; set; }

    /// <summary>
    /// 表示验证成功 (true 如果验证成功，否则为 false)
    /// </summary>
    public static readonly ValidationResult Success = new ValidationResult(true, string.Empty);

    /// <summary>
    /// ctor
    /// </summary>
    /// <param name="isValid"></param>
    /// <param name="errorMessage"></param>
    public ValidationResult(bool isValid, string errorMessage) {
      this.IsValid = isValid;
      this.ErrorMessage = errorMessage;
    }
  }
}
